package edu.cuit.avatar.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/14 10:08
 */
@Configuration
@ComponentScan(basePackages = "edu.cuit.avatar")
@PropertySource(value = "classpath:jdbc.properties", encoding = "utf-8")
@EnableTransactionManagement
public class SpringConfig {
    /**
     * 配置数据源
     */
    @Bean
    public DataSource dataSource(@Value("${driverClassName}") String driverClassName,
                                 @Value("${url}") String url,
                                 @Value("${jdbc.username}") String username,
                                 @Value("${password}") String password,
                                 @Value("${defaultAutoCommit}") boolean defaultAutoCommit,
                                 @Value("${connectionProperties}") String connectionProperties){
        var dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDefaultAutoCommit(defaultAutoCommit);
        dataSource.setConnectionProperties(connectionProperties);
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public TransactionManager transactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}
